﻿using System;
using System.Net;
using System.Globalization;
using System.Linq;
using HtmlAgilityPack;
using ScheduleMVVM.Model.RuntimeFramework;

namespace ScheduleMVVM.Model.PersistentFramework
{
    public class TUTUruEngine : BaseEngine
    {
        public override String GetQueryString(StationEntry StartStation, StationEntry EndStation)
        {
            return "http://tutu.ru/rasp.php?st1=" + StartStation.id.ToString() + "&st2=" + EndStation.id.ToString() + "&date=" + DateTime.Today.Day.ToString() + "." + DateTime.Today.Month.ToString()
                + "." + DateTime.Today.Year.ToString();
        }
        public override ScheduleParseResult GetEntriesFromHtmlDocument(string document, System.Collections.Generic.List<DataItem> resultList, out Exception error, out ErrorCause cause)
        {
            error = null;
            cause = ErrorCause.NO_ERROR;
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(document);
            if (IsNoDirectTransition(htmlDocument))
            {
                return ScheduleParseResult.NO_TRANSITION;
            }
            Boolean finished = false;
            try
            {
                if(!finished) TryParseBasicLayout(resultList, htmlDocument);
                finished = true;
            }
            catch (Exception e) { 
                error = e;
                cause = ErrorCause.PARSE_ERROR;
            }
            try
            {
                if (!finished) TryParseTrasferLayout(resultList, htmlDocument);
                finished = true;
            }
            catch { }
            // TODO: Add more handlers
            if (!finished)
            {
                resultList.Clear();
                return ScheduleParseResult.FAILURE;
            }
            else
            {
                return ScheduleParseResult.COMPLETE;
            }            
        }
        private static Boolean IsNoDirectTransition(HtmlDocument htmlDocument)
        {
            return htmlDocument.DocumentNode.InnerText.Contains("пересадками");
        }
        private static void TryParseBasicLayout(System.Collections.Generic.List<DataItem> resultList, HtmlDocument htmlDocument)
        {
            CultureInfo cultureInfo = new CultureInfo("ru-RU");
            var dateTimeInfo = cultureInfo.DateTimeFormat;
            var WebTableNode = htmlDocument.GetElementbyId("schedule_table");
            var WebTBodyNode = WebTableNode.ChildNodes.Where(x => x.Name == "tbody");
            var WebTRNodes = WebTBodyNode.First<HtmlNode>().ChildNodes.Where(x => x.Name == "tr");
            foreach (var i in WebTRNodes)
            {
                if (i.Id != "") break;
                DateTime arrival, departure;
                Int32 trainID = 0;
                // Get data
                var WebTDCollection = i.ChildNodes;
                String DepartureString = WebTDCollection[3].ChildNodes[7].InnerText;
                String Platform = DetectPlatform(DepartureString);
                if (Platform != String.Empty) departure = DateTime.Parse(DepartureString.Split('(')[0], dateTimeInfo);
                else
                    departure = DateTime.Parse(WebTDCollection[3].ChildNodes[7].InnerText, dateTimeInfo);
                arrival = DateTime.Parse(WebTDCollection[7].ChildNodes[1].InnerText, dateTimeInfo);
                // Form entry
                var _entry = new DataItem()
                {
                    id = trainID,
                    Departure = departure,
                    Arrival = arrival,
                    RouteFromString = WebTDCollection[19].ChildNodes[1].InnerText,
                    RouteToString = WebTDCollection[23].ChildNodes[1].InnerText,
                    DeparturePlatform = Platform
                };
                resultList.Add(_entry);
            }
        }

        private static String DetectPlatform(String DepartureString)
        {
            String Platform;
            if (DepartureString.Contains("пл."))
            {
                Platform = DepartureString.Split('(')[1].Replace(")", "").Replace("&nbsp;", "").Replace("&#x0;","");
            }
            else Platform = String.Empty;
            return Platform;
        }
        private static void TryParseTrasferLayout(System.Collections.Generic.List<DataItem> resultList, HtmlDocument htmlDocument)
        {
            throw new NotImplementedException();
        }
        public TUTUruEngine()
        {
            ClassName = "TUTUruEngine";
            Title = "tutu.ru based engine";
            Website = "http://tutu.ru";
            FavouritesStore = "fav_tuturuengine.xml";
            StationsStore = "stations_tuturuengine.xml";
        }
    }
}
